import axios from 'axios';

const instance = axios.create({
    baseURL: 'http://127.0.0.1:3000',
    timeout: 5000,
});

instance.interceptors.request.use(
    (config) => {
        config.headers.token = localStorage.getItem('token') || ''
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

instance.interceptors.response.use(
    (response) => {
        const data = response.data;
        if (data.code !== 200) {
            console.error(`Error: ${data.message}`);
        }
        return data;
    },
    (error) => {
        console.error('Response Error:', error);
        return Promise.reject(error);
    }
);

function get(url, params = {}) {
    return instance.get(url, { params });
}

function post(url, data = {}) {
    return instance.post(url, data);
}

function uploadFile(url, file) {
    const formData = new FormData();
    formData.append('file', file);
    return instance.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
        },
    });
}

const http = (url, method, params = {})=> {
    if(method == "get") {
       return get(url, params)
    }else if(method == "post") {
        return  post(url, params)
    }else if(method == "upload") {
        return  uploadFile(url, file)
    } 
}

export default http